//
//  File.swift
//
//
//  Created by didi on 2022/9/9.
//

import Fluent
import MolecularObjects
import Vapor

struct SystemPermissionRepository: MolecularModelRepository {
    typealias DatabaseModel = SystemPermissionModel

    public private(set) var db: Database

    init(_ db: Database) {
        self.db = db
    }

    // MARK: - additional query methods

    func get(_ permission: Permission) async throws -> DatabaseModel? {
        try await DatabaseModel.query(on: db)
            .filter(\.$namespace == permission.namespace)
            .filter(\.$context == permission.context)
            .filter(\.$action == permission.action.key)
            .first()
    }

    func get(_ key: String) async throws -> DatabaseModel? {
        try await get(.init(key))
    }

    func isUnique(_ permission: Permission, id: UUID? = nil) async throws -> Bool {
        var query = SystemPermissionModel.query(on: db)
            .filter(\.$namespace == permission.namespace)
            .filter(\.$context == permission.context)
            .filter(\.$action == permission.action.key)

        if let modelId = id {
            query = query.filter(\.$id != modelId)
        }
        let count = try await query.count()
        return count == 0
    }
}
